import { defineStore } from 'pinia'
import { ref } from 'vue'

const initState = { nickname: '', avatar: '', phone: '', userType: 0, userId: '', openId: '' }

export const useUserStore = defineStore(
  'user',
  () => {
    const showModal = ref<boolean>(false) // 登录弹窗是否显示
    const token = ref<string>('') // token
    const userInfo = ref<IUserInfo>({ ...initState })

    // 获取用户信息
    const getUserInfo = () => {
      return new Promise((resolve, reject) => {
        http
          .get('/blade-auth/wx/getAppUser')
          .then((res: any) => {
            resolve(res)
            setUserInfo({
              userId: res.userId,
              nickname: res.nickName,
              userType: res.userType,
              avatar: res.avatar,
              phone: res.phone,
              openid: res.openId,
            })
          })
          .catch((err) => {
            reject(err)
          })
      })
    }

    const setUserInfo = (val: IUserInfo) => {
      userInfo.value = val
    }

    const setToken = (t: string) => {
      token.value = t
    }

    const clearUserInfo = () => {
      token.value = ''
      userInfo.value = { ...initState }
    }

    const isLogged = computed(() => !!token.value)

    function setShowModal(state) {
      showModal.value = state
    }
    return {
      showModal,
      setShowModal,
      token,
      setToken,
      userInfo,
      setUserInfo,
      getUserInfo,
      clearUserInfo,
      isLogged,
    }
  },
  {
    persist: true,
  },
)
